Lorem ipsum dolor sit amet
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu.
你可以 點擊這里下載, 引入 jQuery 和 Tooltipster's CSS 還有 JavaScript 文件在你的頁面
<head> <link rel="stylesheet" type="text/css" href="tooltipster/css/tooltipster.bundle.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script type="text/javascript" src="tooltipster/js/tooltipster.bundle.min.js"></script> </head>
兼容提醒: jQuery 1.7已經足夠了,除非你需要SVG兼容IE(需要使用jQuery 1.10+). Tooltipster 不能正常運行在IE9中引用jQuery1.8
想讓一個元素加入工具提醒, 我們會給他加上一個類名class 'tooltip' . 你也可以選擇使用自定義的類名或選擇器(請繼續往下看), 由你決定. 之后, 我們將設置標題title 屬性為我們想要的提示. 這里有幾個栗子:
// 在圖片加入工具提醒: <img src="my-image.png" class="tooltip" title="This is my image's tooltip message!" /> // 在文字加入工具提醒 (span, div or whatever): <span class="tooltip" title="This is my span's tooltip message!">Some text</span>
注意:如果您使用Twitter's Bootstrap,請使用另一個類名,因為“工具提示”會產生沖突。
我們要做的最后一件事是激活Tooltipster. 我們需要在頭部得問 </head> 標簽加入script并激活Tooltipster (你可以選擇使用自己定義的選擇器 - 我們的栗子是使用 'tooltip' class):
<head> ... <script> $(document).ready(function() { $('.tooltip').tooltipster(); }); </script> </head>
第一個是默認樣式, Tooltipster還為你提供另外五種主題風格.
要使用這些主題,需要引用一個css文件 (他的路徑是 css/plugins/tooltipster/sideTip/themes 文件里) 在你的頁面并指定其名稱在Tooltipster's 選項
$('.tooltip').tooltipster({ theme: 'tooltipster-noir' //使用Noir主題 });
你可以通過修改tooltips的樣式達到你想要的效果, 自定義主題部分 在下面等著你.
注: "sideTip" 是 Tooltipster默認插件的名稱. 我們稍后會看到這個插件.
Tooltipster 允許你使用任何HTML標記觸發提醒. 這意味著可以插入像圖像和文本格式標記之類的東西。.
代替之前加入的title 屬性, 這次我們使用 data-tooltip-content 屬性來提供與HTML頁面內對應的元素選擇器,該元素作為內容顯示. 栗子如下:
<span class="tooltip" data-tooltip-content="#tooltip_content">This span has a tooltip with HTML when you hover over it!</span> <div class="tooltip_templates"> <span id="tooltip_content"> <img src="myimage.png" /> <strong>This is the content of my tooltip!</strong> </span> </div>
在你的CSS文件, 加入 .tooltip_templates { display: none; } 這樣內容不會在工具提示之外顯示出來.
重點: 如果你有兩個(或以上)的tooltips有相同的 data-tooltip-content 屬性 (也就是說, 你想用一樣的HTML元素), 請將 contentCloning 選項設置為 true 當你初始化你的tooltips:
$('.tooltip').tooltipster({ contentCloning: true });
注: 其實還有其他設置提醒內容的方法.
Tooltipster的功能可以通過插件擴展.他們可能會增加新的風格,新的選擇,新的方法,新的行為,等等.
Tooltipster的一些流行插件:
sideTip Tooltipster附帶的和默認啟動的
SVG Tooltipster附帶的, 增加了 SVG 支持, 但是默認情況是不啟動的 (詳情見SVG section)
follower 讓工具提示跟隨光標 有空看看這
scrollableTip 使工具提示增加滾動條當內容過多. 請看這
discovery 創建工具提示組更快顯示 ,在分組提示 部分顯示, 可以看這
selectableText 當你選擇/高亮某段文字,讓工具提醒顯示. 詳情見此
有關插件的更多信息,請閱讀我們的。插件部分.
Tooltipster 的參數(選項)給你一個寬闊的可變范圍來調整成你心儀的提醒. 這里教你如何配置參數:
$('.tooltip').tooltipster({ animation: 'fade', delay: 200, theme: 'tooltipster-punk', trigger: 'click' });
這里是全部可用參數的列表:
參數 | 可用的值 | 描述 |
animation |
'fade', 'grow', 'swing', 'slide', 'fall' |
決定tooltips進場的動畫. 除了內置的動畫, 你也可以創建自定義動畫在你的CSS文件. 在IE9及以下, 所有動畫默認為javascript生成淡入動畫. 默認值: 'fade' |
animationDuration |
integer, integer[] |
設置動畫的持續時間, 以毫秒為單位. 如果你想為你的tooltips打開/關閉提供不同的持續時間, 你可以提供一個數組來表示不同的值(如:integer[400,500]). 默認值: 350 |
arrow |
boolean | 給你的tooltips加一個"氣泡" 箭頭. 默認值: true |
content |
string, jQuery object, any |
如果設置了, 將會覆蓋tooltips的內容. 如果您提供的內容不是字符串或jQuery封裝的HTML元素,你需要使用'functionFormat'這個參數來格式化你的內容以達到顯示效果默認值: null |
contentAsHTML |
boolean | 如果tooltip的內容是字符串, 會默認顯示為純文本. 如果想將內容解析為HTML, 請將這個參數設為true. 默認值: false |
contentCloning |
boolean | 如果你提供了一個JQ對象給'content'這個參數,如果這個克隆對象應該被使用,則設置此參數.默認值: false |
debug |
boolean | 當你做了你不應該做的事情,tooltipster日志提醒和通知會在控制臺報錯,如果你設置了false便可以禁用日志記錄默認值: true |
delay |
integer, integer[] |
在鼠標交互的時候,這個屬性是在hover/trigger..觸發tooltip開始打開或者關閉動畫使用時生效(簡單來說就是一個延時器)(*). 如果你想為你的tooltips打開/關閉提供不同的持續時間, 你可以提供一個數組來表示不同的值(如:integer[400,500]).默認值: 300 |
delayTouch |
integer, integer[] |
在觸摸交互的時候, 同上(*).如果你想為你的tooltips打開/關閉提供不同的持續時間, 你可以提供一個數組來表示不同的值(如:integer[400,500]). 默認值: [300, 500] |
distance |
integer, integer[] |
以像素為單位,遠點到提醒工具的距離.如果您希望為每個邊指定不同的距離,則該值可以是整數或整數數組(通常為CSS語法)。 默認值: 6 |
functionInit |
function | 在實例化時只被觸發一次的自定義函數. Arguments. 默認值: none (null) |
functionBefore |
function | 在打開工具提示之前要觸發的自定義函數. 這個發方法會阻止tooltip打開如果返回false.Arguments. 默認值: none (null) |
functionReady |
function | 當工具提示及其內容被添加到DOM時,將觸發自定義函數. Arguments. 默認值: none (null) |
functionAfter |
function | 一旦工具提示已關閉并從DOM中移除,則將定制一個函數.Arguments. 默認值: none (null) |
functionFormat |
function | 格式化內容的函數.它得到兩個第一個通常的參數和第三個參數的內容。它必須返回在工具提示中顯示的值,無論是字符串還是jQuery封裝的HTML元素(請參閱格式化部分). 默認值: none (null) |
functionPosition |
function | 當tooltip重新定位時觸發的自定義函數,它給你輕微或完全修改的位置,Tooltipster是要給tooltip的能力,它將建議的放置值集設置為第三個參數.函數必須返回您可能編輯過的位置值集合(請參閱定位部分). 默認值: none (null) |
IEmin |
integer | 要運行的IE的最低版本. 默認值: 6 |
interactive |
boolean | 在工具提醒給用戶盡可能多的交互.如果你想他們在工具提醒內容可以點擊,填寫表格或者其他交互,你就必須把這個參數設置為true.當使用“懸停”關閉觸發器時,用戶必須在開始關閉之前將光標移到工具提示上(此時間間隔由“delay”參數設置). 默認值: false |
maxWidth |
integer | 設置tooltip的最大寬度. 默認值: null (無限制) |
minIntersection |
integer | 對應于箭頭中心和工具提示邊緣之間強制執行的最小距離. 主要用于創建大于默認主題的箭頭. 默認值: 16 |
minWidth |
integer | 設置tooltip的最小寬度.默認值: 0 (auto width) |
multiple |
boolean | 允許你把幾個提示在一個單一的元素 (詳見 multiple 部分). 默認值: false |
plugins |
string[] | 設置使用Tooltipster的插件名. 默認值: ['sideTip'] |
repositionOnScroll |
boolean | 為了使tooltip盡可能長時間可見,重新定位tooltip如果它在用戶滾動頁面時退出視窗. 默認值: false |
restoration |
'none', 'previous', 'current' |
指定在調用“銷毀”方法后,是否應該在HTML元素上恢復title屬性.這個屬性可以省略,或是在Tooltipster之前初始化存在的值恢復,或是與字符串化值的當前內容恢復.注意:在多個工具提示的情況下在一個單一的元素,只有最后的破壞可能會觸發恢復提示. 默認值: 'none' |
selfDestruction |
boolean | 在這個原點從DOM移除后,設置這個參數是否將tooltip自毀.這可以防止內存泄露. 默認值: true |
side |
string, string[] |
設置tooltip在哪側顯示. 這個值可能是一個: 'top', 'bottom', 'left', 'right'. 也可以是一個數組包括多個值. 當使用數組時,這些值的順序要考慮到回退順序和禁用沒有用到的一側 (see the sides section). 默認值: ['top', 'bottom', 'right', 'left'] |
timer |
integer | 設置這個工具提醒在關閉前的顯示時間(以毫秒為單位) 默認值: 0 (disabled) |
theme |
string, string[] |
設置一個將覆蓋默認工具提示外觀的主題. 你可以提供多個字符串的數組來同時應用多個主題Y(詳見 主題部分). 默認值: empty array |
trackerInterval |
integer | 設置追蹤程序持續時間/毫秒(見trackOrigin 和 trackTooltip).當工具提醒被打開,即使trackOrigin和trackTooltip設置為false,追蹤器運行會檢查起點是否被移除,如非必要,你定的值不能太高或太低. 默認值: 500 |
trackOrigin |
boolean | 如果原點移動或調整大小需要復位提醒.由于此選項可能對性能有影響,我們建議您僅在需要時啟用它. 默認值: false |
trackTooltip |
boolean | 如果tooltip改變大小則重新配置tooltip.當尺寸受到'content'這個方法而改變尺寸,tooltip已經重新定位而不需要這個參數。由于此選項可能對性能有影響,我們建議您僅在需要時啟用它。詳情進入這個入口 有常見問題解答 默認值: false |
trigger |
'hover', 'click', 'custom' |
設置這個觸發條件,有'click','hover',還可以自定義以達到你想要的效果. 見 觸發器部分 來學習如何使用自定義觸發器. 默認值: 'hover' |
triggerClose |
object | 當你把'trigger'設置為'custom',所有內置關閉觸發器都默認不可用,此參數就是允許您激活您所選擇的觸發器來創建一個定制的行為,只在設置'trigger'為'custom'時有效。 詳見觸發器部分. |
triggerOpen |
object | 類似于'triggerClose'(同上). |
updateAnimation |
'fade', 'rotate', 'scale', null |
用于打開tooltip后的后續動畫設置,你可以創建自己的動畫在您的CSS文件內但是要將值設為'null'. 默認值: 'rotate' |
viewportAware |
boolean | 嘗試將tooltip放置在屏幕打開時完全可見的地方,如果工具提示在其源于屏幕之外(使用方法調用)打開時,您可能希望將此選項設置為false。默認值: true |
zIndex |
integer | 設置tooltip的z-index默認值: 9999999 |
幾乎所有用戶的回調函數有相同的特征. 這意味著 functionInit, functionBefore, functionReady, functionAfter, functionFormat, functionPosition and the open and close 回調都得到了這兩個參數:
// this is valid for the other callback functions too functionInit(instance, helper){ ... }
小例外: functionFormat 和 functionPosition 獲取額外的第三個參數(以上記載)。
instance 是調用回調函數對象和Tooltipster 面向對象部分object-oriented section的描述.
helper 是一個對象,其中包含您可能會發現有用的變量. For example:
helper.origin is always present, it's the HTML element on which the tooltip is set.
helper.tooltip is present in functionReady and open callbacks, it's the root HTML element of the tooltip. In other callbacks, it is undefined.
helper.event is present in functionBefore and functionAfter callbacks. It's the mouse or touch event that triggered the opening or the closing of the tooltip. When the action was not triggered by a mouse or touch event, this variable is null or undefined.
For advanced use cases, Tooltipster offers a set of methods to manipulate your tooltips. They allow you to create custom triggers, update tooltip content on the fly (whether the tooltip is currently open or not), destroy Tooltipster functionality if needed, reposition tooltips and more.
Instance methods are used to manipulate one tooltip in particular. There are two ways to call them.
1) Through the origin's HTML element: $('#my-tooltip').tooltipster(methodName [, argument1] [, argument2]);
2) Through the tooltip instance, when you have it: instance.methodName([argument1] [, argument2]);
The latter will be discussed in the object-oriented section. Users with simple use cases just need to know that it's the recommended way of calling methods when you are inside functionInit, functionBefore and the like. Here is the list of instance methods:
Method name | Arguments | Description |
close |
callback | Closes the tooltip. When the animation is over, its HTML element is destroyed (definitely removed from the DOM). The `callback` function argument is optional (see its input signature). |
content (getter) |
None | Returns a tooltip's current content. If the selector matches multiple origins, only the value of the first will be returned. |
content (setter) |
content | Updates the tooltip's content. |
destroy |
None | Closes and destroys the tooltip functionality. |
disable |
None | Temporarily disables a tooltip from being able to open. |
elementOrigin |
None | Returns the HTML element which has been tooltipped. |
elementTooltip |
None | Returns the HTML root element of the tooltip if it is open, `null` if it is closed. |
enable |
None | If a tooltip was disabled, restores its previous functionality. |
instance |
None | Returns the instance of Tooltipster associated to the tooltip. If the selector matches multiple origins, only the instance of the first will be returned. |
on, one, off, triggerHandler |
callback | Handle Tooltipster's events on a per-instance basis (see the events section). |
open |
callback | Opens the tooltip. The `callback` function argument is optional (see its input signature) and, if provided, is called when the opening animation has ended. |
option (getter) |
optionName | Returns the value of an option. |
option (setter) |
optionName, optionValue | Sets the value of an option (for advanced users only; we do not provide support on unexpected results). |
reposition |
None | Resizes and repositions the tooltip. |
status |
None | Returns various information about the tooltip, like whether it is open or not. See the status section. |
Example of the first syntax:
// initialize your tooltip as usual: $('#my-tooltip').tooltipster({}); // at some point you may decide to update its content: $('#my-tooltip').tooltipster('content', 'My new content'); // ...and open it: $('#my-tooltip').tooltipster('open'); // NOTE: most methods are actually chainable, as you would expect them to be: $('#my-other-tooltip') .tooltipster({}) .tooltipster('content', 'My new content') .tooltipster('open');
Example of the second syntax:
$('.tooltip').tooltipster({ functionBefore: function(instance, helper) { instance.content('My new content'); } });
Core methods are methods which may affect/handle several tooltips at once. You call them with: $.tooltipster.methodName([argument]);
Method name | Arguments | Description |
instances |
None OR selector OR HTML element |
Returns the instances of Tooltipster of all tooltips set on the element(s) matched by the argument. If there is no argument, then all instances of all tooltips present in the page are returned. |
instancesLatest |
None | Returns the instances of Tooltipster which were generated during the last initializing call. |
on, one, off, triggerHandler |
Handle Tooltipster's events coming from any instances. See the events section. | |
origins |
None OR selector |
Returns an array of all HTML elements in the page which have one or several tooltips initialized. If a selector is passed, the results will be limited to the descendants of the matched elements. |
setDefaults |
options | Changes the default options that will apply to any tooltips created from now on. |
Examples:
// Set default options for all future tooltip instantiations $.tooltipster.setDefaults({ side: 'bottom', ... }); // The `instances` method, when used without a second parameter, allows you to access all tooltips present in the page. // That may be useful to close all tooltips at once for example: var instances = $.tooltipster.instances(); $.each(instances, function(i, instance){ instance.close(); }); $('.tooltip1').tooltipster(); $('.tooltip2').tooltipster(); // this method call will only return an array with the instances created for the elements that matched '.tooltip2' because that's the latest initializing call. var instances = $.tooltipster.instancesLatest();
Tooltipster makes it very easy to go from one of the packaged themes and customize a few properties of your choice. To do so, we recommend that you create a so-called "secondary theme" which will override some properties of a packaged theme.
Create a new css file and include it in your page. Inside the file, declare your customized rules like this:
/* This is how you would create a custom secondary theme on top of tooltipster-noir: */ .tooltipster-sidetip.tooltipster-noir.tooltipster-noir-customized .tooltipster-box { background: grey; border: 3px solid red; border-radius: 6px; box-shadow: 5px 5px 2px 0 rgba(0,0,0,0.4); } .tooltipster-sidetip.tooltipster-noir.tooltipster-noir-customized .tooltipster-content { color: blue; padding: 8px; }
For your secondary theme to be applied, provide an array of themes instead of just one. You may even provide more than two themes if you create a secondary theme to your secondary theme! In other words, this allows sub-themes, sub-sub-themes, etc. for your tooltips.
$('.tooltip').tooltipster({ theme: ['tooltipster-noir', 'tooltipster-noir-customized'] });
Changing the size of the arrow might be the only challenging customization but it's doable! We encourage you to see what we have done in the different themes and work from there.
It's easy as pie to update a tooltip's content - whether it's open or closed. Depending on your selector, you can update multiple tooltips at once or just one:
$('#myelement').tooltipster('content', 'My new content'); // or when you have the instance of the tooltip: instance.content('My new content');
Tooltipster plays a subtle animation when the content changes. This animation may be changed or disabled through the updateAnimation option.
Tooltipster gives you the ability to fire a custom function when a tooltip is initialized (functionInit), but also every time the tooltip is about to open (functionBefore), when it has opened (functionReady) or after it has closed (functionAfter).
One great use for this is to grab dynamic content for your tooltips via AJAX. In this example we will use functionBefore to load data the first time the tooltip is opened. Until the data has been loaded, we will display a "Loading..." notification:
$('.tooltip').tooltipster({ content: 'Loading...', // 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section. functionBefore: function(instance, helper) { var $origin = $(helper.origin); // we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens if ($origin.data('loaded') !== true) { $.get('http://example.com/ajax.php', function(data) { // call the 'content' method to update the content of our tooltip with the returned data. // note: this content update will trigger an update animation (see the updateAnimation option) instance.content(data); // to remember that the data has been loaded $origin.data('loaded', true); }); } } });
In addition to this, you may provide a function as the callback argument of the open/close methods. If the tooltip is already in the state you are asking for (open & stable/closed), the callback is executed immediately. Please note that if the open/close action is somehow cancelled before it has completed its animation, the callback function will never be called.
$(document).ready(function() { $('.tooltip').tooltipster(); $('#example').tooltipster('open', function(instance, helper) { alert('The tooltip is now fully shown. Its content is: ' + instance.content()); }); $(window).keypress(function() { $('#example').tooltipster('close', function(instance, helper) { alert('The tooltip is now fully hidden'); }); }); });
Let's hover a little on how the side option works.
You have two options: provide either a string, like side: 'top', or an array of strings, like side: ['top', 'bottom'] for example.
This tells Tooltipster that you'd prefer the tooltip to be above the tooltipped element, but allows the tooltip to be positioned differently if need be.
This means that if there is not enough space on top for your tooltip, the other sides may be used a fallbacks. Here is the order of fallbacks, depending on what side you chose:
// ... is the same as ... 'top' => ['top', 'bottom', 'right', 'left'] 'bottom' => ['bottom', 'top', 'right', 'left'] 'right' => ['right', 'left', 'top', 'bottom'] 'left' => ['left', 'right', 'top', 'bottom']
There are two reasons to do so.
Firstly, if you are not happy with the four default orders of sides fallbacks. For example you might want: side: ['top', 'left', 'bottom', 'right'].
Secondly if you want to disable totally one or more sides. For example, with ['top', 'right', 'left'], the tooltip will never be positioned on the bottom. With ['right'], the tooltip will always be on the right, even if it has to overflow the document.
The easiest way to set when a tooltip should open or close is to set the trigger option to one of the two predefined values: 'hover' or 'click'.
You can see how they perform with our demos at the top of this page. Note that these two behaviors also apply to their touch-gesture equivalents.
If you feel that you need a different behavior or more flexibility, set the trigger option to 'custom' and read on.
There are many actions that may cause a tooltip to open or close, should we want to. These action are called "open triggers" and "close triggers".
Tooltipster supports a number of them out of the box, the list lies below. Plugins may provide support for additional triggers.
click When the origin is clicked by a mouse.
mouseenter When a mouse comes over the origin. The delay option is taken into account as the delay before opening.
touchstart When the origin is pressed on a touch screen. The delayTouch option is taken into account as the delay before opening.
tap When the origin is tapped (ie pressed and then released) on a touch screen.
click When a mouse click happens anywhere in the page. However, if the interactive option is set to true, a click happening inside the tooltip will not close it.
mouseleave When the mouse goes away from the origin. The delay option is taken into account as the delay before closing.
originClick When the origin is clicked by a mouse. This mimics a behavior that browsers usually have and is meant to be used with the mouseenter open trigger.
scroll When scrolling happens in the window or in a scrollable area which is a parent of the origin.
tap When the finger taps (ie presses and releases) anywhere in the touch screen.
touchleave When the finger is removed from the touch screen or if the interaction was stopped by the device. The delayTouch option is taken into account as the delay before closing.
Once that the trigger option is set to 'custom', all open and close triggers are disabled by default. Use the triggerOpen and triggerClose options to reactivate the triggers of your choice, as shown below.
Let's assume that you'd like a tooltip to open upon mouse hovering, but close only when either a mouse click or scrolling happens. Write this:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true }, triggerClose: { click: true, scroll: true } });
This works well on desktops but not on touch devices, because we have not enabled any touch triggers. Let's fix this by enabling the touchstart and tap triggers as well:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { click: true, scroll: true, tap: true } });
Good question. Setting trigger: 'hover' or trigger: 'click' is nothing but a shorthand.
Having trigger: 'hover' is actually the same as having:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { mouseleave: true, originClick: true, touchleave: true } });
And having trigger: 'click' is the same as having:
$('#example').tooltipster({ trigger: 'custom', triggerOpen: { click: true, tap: true }, triggerClose: { click: true, tap: true } });
In parallel to (or instead of) using the built-in triggers, you may want to open/close a tooltip yourself on a specific occasion.
To achieve this, Tooltipster has the open and close methods. Both of them may receive an optional callback argument, which represents a function you'd like to be called when the tooltip is done animating.
Here's an example of how you could launch a specific tooltip on page load and close it when any key on your keyboard is pressed.
<span id="example" class="tooltip" title="My tooltip content">Example</span>
$(document).ready(function() { // first on page load, initialize all tooltips $('.tooltip').tooltipster(); // then immediately open the tooltip of the element named "example" $('#example').tooltipster('open'); // as soon as a key is pressed on the keyboard, close the tooltip. $(window).keypress(function() { $('#example').tooltipster('close'); }); });
This is for advanced users who are comfortable with Javascript and CSS.
When the tooltip needs to be positioned or repositioned, Tooltipster runs all kinds of tests to find the best option. But before the computed position is applied, you have the option to edit it using the functionPosition option.
When you provide custom coordinates for the tooltip and its arrow, they have to be relative to the top and left edges of the viewport. This makes custom positioning in Tooltipster both very fast and very simple. Doing your calculations, element.getBoundingClientRect will become your new best friend, so make sure you check it out.
Your functionPosition callback is called with three parameters. The first two ones are instance and a helper, as usual. The third argument is an object with the position properties proposed by Tooltipster, that you may edit. You must return the edited third argument for the changes to get applied.
helper.mode (will be 'natural' or 'constrained') indicates if Tooltipster adapted the size of the tooltip for it to fit in.
helper.tooltipClone is a clone of the tooltip which exists in the DOM at the time the callback is called.
helper.geo includes useful pre-calculated data about the page layout. It will help you avoid putting the tooltip accidentally off screen, for example. This object is in this form:
{ document: { size: { height: integer, width: integer } }, window: { scroll: { left: integer, top: integer }, size: { height: integer, width: integer } }, origin: { // the origin has a fixed lineage if itself or one of its ancestors has a fixed position fixedLineage: boolean, offset: { // this is the distance between the bottom side of the origin and the top of the document bottom: integer, left: integer, // this is the distance between the right side of the origin and the left of the document right: integer, top: integer }, size: { height: integer, width: integer }, // if the origin is a map area, this will hold the associated image element usemapImage: HTMLobject || null, windowOffset: { // this is the distance between the bottom side of the origin and the top of the viewport bottom: integer, left: integer, // this is the distance between the right side of the origin and the left of the viewport right: integer, top: integer } } }
The third argument is in the form:
{ coord: { left: number, top: number }, distance: number, side: string, size: { height: number, width: number }, target: number }
coord properties determine the position of the tooltip and are relative to the viewport.
distance is the offset that will be applied between the origin and the tooltip.
side is the side Tooltipster has judged best for your tooltip, according to your requirements.
size properties tell you the size that your tooltip will have. It is either the natural size of the tooltip, or a size that has been set by Tooltipster to fit best on screen according to your requirements.
target represents the location Tooltipster thinks the tooltip should ideally be centered on, and the arrow aiming at. It is given as the distance from the relevant edge of the viewport (left edge if the side is "top" or "bottom", top edge if the side is "left" or "right"). The target is usually the middle of the origin, but can be somewhere else when the origin is actually a portion of text split in several lines. Editing this value will change the location the arrow is aiming at but will not change the position of the tooltip itself (use coord for that).
You may look at the source code of this documentation to see how the custom positioning demo at the top of this page was made. Here is the simplest example, let's just move the tooltip by 10 pixels to the bottom-right:
$('#my-tooltip').tooltipster({ functionPosition: function(instance, helper, position){ position.coord.top += 10; position.coord.left += 10; return position; } });
Instead of using the data-tooltip-content attribute, you may:
$('#tooltip').tooltipster({ content: $('#tooltip_content'), // if you use a single element as content for several tooltips, set this option to true contentCloning: false });
Tooltipster's content method allows you to edit the content of the tooltip at any time with greater flexibility. If you had this HTML for example:
<div class="tooltip"> This div has a tooltip with HTML when you hover over it! <span class="tooltip_content"> <img src="myimage.png" /> <strong>This is the content of my tooltip!</strong> </span> </div>
You could do this upon initialization:
$('.tooltip').tooltipster({ functionInit: function(instance, helper){ var content = $(helper.origin).find('.tooltip_content').detach(); instance.content(content); } });
If you write encoded HTML in the title attribute and set the contentAsHTML option to true, it will be displayed as HTML in the tooltip.
You may want to write options on a per-tooltip basis, directly in your HTML. Of course, you should try to do this for options which are "inlinable" only. Anyway, that's a great opportunity to make use of the functionInit option and the option method, here's how it goes:
<span class="tooltip" data-tooltipster='{"side":"left","animation":"slide"}' title="Hello">World</span>
$('.tooltip').tooltipster({ functionInit: function(instance, helper){ var $origin = $(helper.origin), dataOptions = $origin.attr('data-tooltipster'); if(dataOptions){ dataOptions = JSON.parse(dataOptions); $.each(dataOptions, function(name, option){ instance.option(name, option); }); } } });
Pro tip: for more flexibility, achieve the same with the event system: $.tooltipster.on('init', function(event) {...});. See the event-driven section.
Sometimes it's easier to work with data sets that you will format before display, rather than format them on the server side. For example, what if you could turn this:
<span id="example" title="We have 3 people today. Say hello to Sarah, John, Matthew">People</span>
into this:
<span id="example" title='["Sarah", "John", "Matthew"]'>People</span>
...with exactly the same result in the tooltip? A first way of doing this is to format upon initialization:
$('#example').tooltipster({ functionInit: function(instance, helper){ // parse the content var content = instance.content(), people = JSON.parse(content), // and use it to make a sentence newContent = 'We have ' + people.length + ' people today. Say hello to ' + people.join(', '); // save the edited content instance.content(newContent); } }); // this logs: "We have 3 people today. Say hello to Sarah, John, Matthew" console.log($('#example').tooltipster('content'));
Simple, right? It works, however this is not ideal for us if we need to get ahold of our data set later. Because as you can see, when we call the content method, we get the computed sentence, not our initial data set. No worries, the functionFormat option is here to help us.
$('#example').tooltipster({ functionInit: function(instance, helper){ var content = instance.content(), people = JSON.parse(content); instance.content(people); }, // this formats the content on the fly when it needs to be displayed but does not modify its value functionFormat: function(instance, helper, content){ var displayedContent = 'We have ' + content.length + ' people today. Say hello to ' + content.join(', '); return displayedContent; } }); // Alright! this logs: ["Sarah", "John", "Matthew"] console.log($('#example').tooltipster('content'));
The status method returns an object that contains information about the tooltip. Here is this object with the meaning of each property:
{ // if the tooltip has been destroyed destroyed: boolean, // if the tooltip is scheduled for destruction (which means that the tooltip is currently closing and may not be reopened) destroying: boolean, // if the tooltip is enabled enabled: boolean, // if the tooltip is open (either appearing, stable or disappearing) open: boolean, // the state equals one of these four values: state: 'appearing' || 'stable' || 'disappearing' || 'closed' }
So far, quite often we called instance methods like this: $(...).tooltipster(methodName). However, advanced users may prefer to handle objects directly rather that go through the DOM to manipulate their tooltips. That's possible with Tooltipster!
Here is an example. This:
$('#my-element').tooltipster(); $('#my-element').tooltipster('open').tooltipster('content', 'My new content');
...can also be written like this:
$('#my-element').tooltipster(); var instance = $('#my-element').tooltipster('instance'); instance.open().content('My new content');
What happened here? The instance method returns the Tooltipster instance that corresponds to the first tooltip set on #my-element. Once we have the Tooltipster instance that corresponds to a tooltip, we can call any methods directly on it to manipulate the tooltip.
If multiple tooltips were set on #my-element using the multiple option (see next section), we'd have to call $.tooltipster.instances('#my-element'); to get an array with all the instances.
As you've seen in many previous examples involving callbacks - either functionInit, functionBefore, etc., open/close callbacks, they all get the Tooltipster instance that calls them as first parameter. So this works fine:
$('#origin').tooltipster({ functionBefore: function(instance, helper){ instance.content('Random content'); } });
While you may feel that this is only nice to have, this notation actually becomes compulsory when you start using multiple tooltips on a same element.
Several independent tooltips can be set on a single element, each one having its own triggers and options. Just set the multiple option to true when you initialize your tooltip. There is just something you need to be aware of when using multiple tooltips:
Calling a method this way: $(...).tooltipster(methodName [, argument]) only ever calls the method on the first tooltip that was set on the element. That's an issue when you actually want to manipulate the second or third tooltip! Make sure you read the previous section as we have to manipulate Tooltipster instances instead to solve this.
var $myElement = $('#my-element'); // create a first tooltip as usual. The multiple option is actually optional for the first tooltip $myElement.tooltipster({ content: 'My first tooltip', side: 'top' }); // initialize a second tooltip $myElement.tooltipster({ // don't forget to provide content here as the first tooltip will have deleted the original title attribute of the element content: 'My second tooltip', multiple: true, side: 'bottom' }); var instances = $.tooltipster.instances($myElement); // use the instances to make any method calls on the tooltips instances[0].content('New content for my first tooltip').open(); instances[1].content('New content for my second tooltip').open(); // WARNING: calling methods in the usual way only affects the first tooltip that was created on the element $myElement.tooltipster('content', 'New content for my first tooltip')
When you provide user callbacks (functionInit, functionBefore etc.), it is also crucial to work with the current instance:
$('#my-element').tooltipster({ content: 'HELLO', functionInit: function(instance, helper) { var string = instance.content(); instance.content(string.toLowerCase()); }, multiple: true });
Live binding does not come out of the box with Tooltipster but is easy to implement if that's what you want.
We chose not to include that option directly because there is no solution that would be both 100% reliable and fast at the same time, and we wanted you to be aware of it before you proceeded. We recommend that you initialize tooltips manually after you create elements that should be tooltipped, in order to avoid any surprises. We do not provide support for issues that might arise from live binding.
If you go the delegation way, you will rely on the bubbling of events (mouseenter or click) triggered on their origin. That may be an issue if these events are stopped from bubbling at some point, and you might run into race conditions depending on how you handle things. And of course, the tooltips won't be initialized until their origin is hovered/clicked, which may be an issue if you wish to manipulate them programmatically or if you use a plugin which is supposed to start working before the tooltip opens.
If you understand these caveats and are willing to proceed, the code below will do the work. You might want to change '.tooltip' to something else and switch from 'mouseenter' to 'click' if you want a click trigger.
$('body').on('mouseenter', '.tooltip:not(.tooltipstered)', function(){ $(this) .tooltipster({ ... }) .tooltipster('open'); });
On the other hand, using mutation observers to initialize tooltips when elements are added to the DOM should completely reliable, but is known to severely hinder the performances of the application. Should you go down this road, feel free to share your code with us and we'll publish it here.
Advanced users may take advantage of the many events that Tooltipster triggers during its tasks. Events and listeners give you more flexibility and greater control over Tooltipster's mechanics.
For example, instead of having to provide a single monolithic callback to functionBefore and the like, events allow you to easily bind and unbind several callbacks at any time. This:
$("#my-tooltip").tooltipster({ functionBefore: function(instance, helper){ doThis(); doThat(); } });
... can be written like that:
var instance = $("#my-tooltip").tooltipster({}).tooltipster('instance'); instance .on('before', doThis) .on('before', doThat);
Set your listeners on a per-instance basis using jQuery's syntax: instance.on(), instance.one(), instance.off() and instance.triggerHandler().
Core listeners that listen to all instances are possible: $.tooltipster.on(), $.tooltipster.one(), $.tooltipster.off(), $.tooltipster.triggerHandler().
Core listeners are great way to set default callbacks without writing something like $.tooltipster.setDefaults({ functionBefore: myFunction }), which could potentially be overriden at initialization. For example, both doThis and doThat will be called here:
$.tooltipster.on('init', function(event){ doThis(); }); $("#my-tooltip").tooltipster({ functionInit: doThat });
Remark: the events are sent to the core listeners first. Besides, the instance emitters and the core emitter are different objects, so unbinding a listener from the core emitter will not unbind it from instance emitters, if you ever bound it to both.
The init, before, ready, after, format and position events will sound familiar: they happen at the same time as their equivalent functionInit, etc.
But there are many others that you or plugin makers can use. Your listeners will get one argument, the event, which holds useful properties: event.type, event.instance, event.origin, event.event (when there is one, similarly to the usual helper.event) and potentially others as described below. These are all the possible events:
before has a special event.stop property which is a function you may call to prevent the tooltip from opening.
close happens at the start of the closing animation. Note: during the animation, the closing may be still cancelled if the tooltip is reopened. The event has a special event.stop property which is a function you may call to ignore the closing order.
closing happens at the end of the closing animation, when you know for sure that the tooltip is about to be closed. If you think you need this event, you may be wrong! When the tooltip is closed, remember that the content is just detached from the DOM and still accessible via the content method.
created is meant for plugin makers and happens when an HTML element has been created for the tooltip.
destroy events happen when the tooltip is closed and about to be destroyed.
destroyed events happen when the tooltip has been destroyed.
dismissable events affect the closing of the tooltip when the mouseleave and touchleave close triggers are used. Read the source for more information.
format has a special event.format property which is a function you may use to format the content before display. Just provide your formatted content as first argument. For your convenience, the original content is provided in the event.content property.
geometry happens when Tooltipster determines the size and coordinates of the origin, in order to know where to place the tooltip. The computed properties (left, top, width and height) are passed in the event.geometry object. It has a special event.edit property which is a function you may use to provide this information yourself. Just provide the edited geometry object as first argument. In some cases, this may be easier to use than functionPosition as it allows you to provide a specific target without having to compute the final position yourself.
init is triggered upon tooltip initialization and may thus be heard only by a core listener.
position happens during the positioning process and can be used to provide a custom position (see functionPosition). The proposed position is present in event.position. The special event.edit property is the function you may call with your edited positioning values as first argument.
positionTest happens before position, while sideTip is still evaluating the different positioning scenarios. While less straightforward to handle, it also brings the possibility to switch between scenarios more easily. As this gets more complex, please read the source code or ask for support about this.
positionTested is related to positionTest.
reposition is meant for plugin makers and happens when Tooltipster thinks the tooltip should be repositioned.
repositioned happens after Tooltipster repositioned of the tooltip. The event has a special event.position with positioning information.
scroll happens whenever a parent of the origin is scrolled. The native scroll event is passed as event.event. If the scroll event was triggered on another element than the window, a special event.geo property gives you information about the page and the origin.
start happens when the mouseenter or touchstart open triggers are used and that the origin gets mouseover/touched. The event has a special event.stop property which is a function you may call to prevent the tooltip from opening.
startcancel happens after start at the end of the opening delay (see the delay option) if the tooltip is not to be opened.
startend happens after start at the end of the opening delay (see the delay option) if the tooltip may be opened.
state happens every time the tooltip enters a different state. The state value is held in event.state and may be 'appearing', 'stable', 'disappearing' or 'closed'.
updated happens when a call to the content method has updated the content. The event has a special event.content property.
Tooltipster is composed of a main script and one or several plugins.
By default, sideTip is the only plugin used by Tooltipster. sideTip takes care of positioning tooltips on a side of their origin.
In fact, the name of our main file is tooltipster.bundle.js because it is a bundle of tooltipster.main and tooltipster-sideTip.
Most of the time, using a plugin requires that you specify its name in the options of the plugin:
$('#example').tooltipster({ plugins: ['pluginNamespace.pluginName'] });
The plugin's namespace exists to resolve conflicts, in case two plugins decided to have the same name, or options/methods of the same name.
Several plugins may be used at the same time and be listed together in the plugins option. However, plugins are sometimes incompatible, for example sideTip and follower (a tooltip obviously can't be positioned on a side and follow the cursor at the same time).
Sometimes, when a plugin adds no options or instance methods, or is auto-activated, you might not have to declare it in the options. Anyway, each plugin will give you its installation instructions.
Under the hood, Tooltipster's plugin system is built on our event system. Plugins register to the core and may react to Tooltipster's many events. A guide for plugin creation is available [here](https://github.com/iamceege/tooltipster/blob/master/plugins.md).
Let us know if you decide to create and share your own plugin, we will list it here!
Several plugins may have the same name. To resolve the conflict, provide the namespace of the plugin when you declare it in the options. You can get the namespace of a plugin by looking at its source file. For example:
$('#example').tooltipster({ plugins: ['laa.follower'] });
Several plugins may have options of the same name. To resolve the conflict, wrap the options of plugins under a property with their full name. For example:
$('#example').tooltipster({ content: 'Hello', theme: 'tooltipster-noir', 'laa.follower': { anchor: 'top-center' }, 'some.otherPlugin': { anchor: 'value' } });
Several plugins may have methods of the same name. To resolve the conflict, use the instance object of the tooltip and specify the full name of the desired plugin in your calls. For example:
$('#example').tooltipster({ functionBefore: function(instance, helper) { instance['laa.follower'].methodName(); } });
The default sideTip plugin adds a few options to Tooltipster. For the sake of simplicity, these options were listed previously among the main options in the Options section. But if you decide not to use sideTip, these options will actually not be available anymore, except if another plugin offers options of the same name. These specific options are:
arrow, distance, functionPosition, minIntersection, minWidth, maxWidth, side, viewportAware
The position, positionTest and positionTested events are also specific to sideTip.
The question comes frequently, so here is the answer: yes, it's possible. Here is an example:
<strong id="nesting">Hover me!</strong>
$('#nesting').tooltipster({ content: $('<span>Hover me too!</span>'), functionReady: function(instance, helper){ // the nested tooltip must be initialized once the first tooltip is open, that's why we do this inside functionReady() instance.content().tooltipster({ content: 'I am a nested tooltip!', distance: 0 }); }, interactive: true });
Result : Hover me!
When the user hovers on adjacent elements one after the other to read their tooltips, you may wish to display the tooltips instantly rather than wait for the default delay and animation times. A demonstration is worth a thousand words, so check out this example:
...and now this one:
This is a good opportunity to demonstrate Tooltipster's powerful features. This is the HTML we wrote:
<input type="button" value="?" title="Add to favorites" class="tooltip tooltip_group" /> <input type="button" value="?" title="Dance in the rain" class="tooltip tooltip_group" /> <input type="button" value="?" title="Play chess" class="tooltip tooltip_group" /> <input type="button" value="?" title="Turn off the computer and meditate" class="tooltip tooltip_group" />
... and the Javascript (which looks long with the comments, but is actually short and simple):
// initialize tooltips in the page as usual $('.tooltip').tooltipster(); // bind on start events (triggered on mouseenter) $.tooltipster.on('start', function(event) { if ($(event.instance.elementOrigin()).hasClass('tooltip_group')) { var instances = $.tooltipster.instances('.tooltip_group'), open = false, duration; $.each(instances, function (i, instance) { if (instance !== event.instance) { // if another instance is already open if (instance.status().open){ open = true; // get the current animationDuration duration = instance.option('animationDuration'); // close the tooltip without animation instance.option('animationDuration', 0); instance.close(); // restore the animationDuration to its normal value instance.option('animationDuration', duration); } } }); // if another instance was open if (open) { duration = event.instance.option('animationDuration'); // open the tooltip without animation event.instance.option('animationDuration', 0); event.instance.open(); // restore the animationDuration to its normal value event.instance.option('animationDuration', duration); // now that we have opened the tooltip, the hover trigger must be stopped event.stop(); } } });
For your convenience, this has been turned into a Tooltipster plugin available here.
If you are going to work with SVG, you'll want to include our SVG plugin that brings fixes and improvements for SVG elements:
<head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script type="text/javascript" src="tooltipster/js/tooltipster.bundle.min.js"></script> <script type="text/javascript" src="tooltipster/js/plugins/tooltipster/SVG/tooltipster-SVG.min.js"></script> </head>
If you want optimal results, you should consider including SVG.js and its ScreenBBox plugin in your page.
Why? Because browsers do not always make our life easy when it comes to working with SVG. Determining the coordinates of SVG paths, polylines or polygons is especially difficult since the native getBoundingClientRect, getBBox and other methods produce inaccurate results in most browsers (as of today in 2016). The result is that by default, the position of tooltips on SVG elements may be completely off. Fortunately, SVG.js helps in that matter and our plugin leverages its power out of the box. Just include the files in your page and that's it, Tooltipster will use them out of the box for optimal results.
For those who seek even more control over positioning, the position event (or the corresponding functionPosition option) and the geometry event allow you to set the exact position of the tooltip yourself.
The W3C issued a recommendation to make websites more accessible to persons with disabilities. This recommendation is known as WAI-ARIA (or simply ARIA), which stands for Web Accessibility Initiative - Accessible Rich Internet Applications.
Accessible tooltips can be powered by Tooltipster. To do this, one solution is to actually manipulate in parallel two tooltips which will share the same content :
- the ARIA tooltip, which is invisible on the screen but readable by ARIA-compatible software
- the Tooltipster tooltip, which is visible on the screen but does not appear as an ARIA-compatible element
A basic example : imagine that we want to put a tooltip on a text input field. As for the HTML part, you would write :
<input id="myfield" type="text" aria-describedby="myfield_description" /> <span id="myfield_description" role="tooltip">Please insert your name here</span>
As for the CSS part, write this :
#myfield_description { position: absolute; visibility: hidden; }
And finally, you could initialize Tooltipster like this :
$('#myfield').tooltipster({ functionInit: function(instance, helper){ var content = $('#myfield_description').html(); instance.content(content); }, functionReady: function(instance, helper){ $('#myfield_description').attr('aria-hidden', false); }, functionAfter: function(instance, helper){ $('#myfield_description').attr('aria-hidden', true); } }); // if in addition you want the tooltip to be displayed when the field gets focus, add these custom triggers : $('#myfield') .focus(function(){ $(this).tooltipster('open'); }) .blur(function(){ $(this).tooltipster('close'); });
Using Tooltipster alongside jQuery Validate by sparky672
Using Tooltipster alongside Clipboard.js
An Angular directive for Tooltipster by campbeln
Did you do something awesome with Tooltipster? Tell us and we'll post it up here!
Please head over to Stackoverflow or another help forum and let the community help you!
Head on over to Tooltipster's issue tracker on GitHub: https://github.com/iamceege/tooltipster/issues
Before opening a new issue, please be sure to search through the backlog to see if your bug has already been submitted. Thank you! :)
Please use the interactive option.
That's because the size of your content inside the tooltip changes after Tooltipster positioned the tooltip.
This typically happens when you put images inside the tooltip. The first time it opens, the image is not loaded yet and thus has no size, so Tooltipster basically computes a position as if there were no images. A few milliseconds later, when the image has loaded, the tooltip gets bigger but is not automatically repositioned. The second time the tooltip opens, the image is already in cache and is ready for display, so Tooltipster can compute an appropriate position.
If the error still occurs, please open an issue on GitHub.
No, it's not Tooltipster's job to tamper with your content in any way. Besides, <script> tags are not the only possible threat (read some good advice).
It's really up to you to decide what should be sanitized before display. You may use functionInit, functionBefore or functionFormat to do so.
These elements do not trigger events anymore when they are disabled, which will cause Tooltipster to malfunction. There is no way around it, so we suggest you make them "look" disabled with CSS and Javascript, but do not set the actual `disabled` property on them. Or you could set pointer-events: none on your disabled element, wrap it in a container and put the tooltip on the container instead.
Tooltipster works "decently" down to IE6. However, these caveats should be noted:
This list is not exhaustive. You may report an issue if you detect one, we will answer but we cannot guaranty that a fix will be provided.
適用瀏覽器:360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗. 不支持IE8及以下瀏覽器。
來源:開優網絡